package xdu.lz.stage1_basic.chapter2_api.d_join_interrupt_wait;

import org.junit.Test;

public class Code06_Interrupt {

    //睡眠被打断
    @Test
    public void testSleep(){
        Thread t1 = new Thread(()->{
            try {
                Thread.sleep(10_000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().getName()+" 睡眠被打断");
            }
            System.out.println("1");
        });
        t1.start();
        //立马打断睡眠,让线程进入runnable状态
        t1.interrupt();

    }

    //这个要放在main方法里才能看出效果
    @Test
    public void testWait(){
        final Object LOCK = new Object();
        Thread t1 = new Thread(()->{
            while (true){
                synchronized (LOCK){
                    try {
                        LOCK.wait(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();

                    }

                }

            }
        });
        t1.start();
        //立马打断睡眠,让线程进入runnable状态
        t1.interrupt();
    }
    public static void main(String[] args){

        Thread mainThread = Thread.currentThread();
        Thread t1 = new Thread(()->{
            while (true){
                System.out.println("start");
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //打断main
                mainThread.interrupt();
                System.out.println(mainThread.isInterrupted());
            }
        });
        t1.start();
        System.out.println(mainThread.isInterrupted());
        try {
            //这是由main执行的，所以是main join了。需要打断main
            t1.join();
            System.out.println("等待join执行完毕，join如果被打断则不会执行");
        } catch (InterruptedException e) {
            System.out.println("main被打断");
            e.printStackTrace();
            System.out.println(mainThread.isInterrupted());
        }

    }
}
